var common = require('../../utils/common.js');
const app = getApp()
Page({
  data: {
    page:1,
    items:[],
    shopInfo:[],
    fromUserId: '',
    freeitems:[],
    userInfo: app.globalData.userInfo,
    statusBarHeight: app.globalData.statusBarHeight,
    currentTab: 0,
    freePage: 1,
    navTab: 0,
    tabNav: [
      {
        name: '小店优选',
        path: '/app/v2/shop/list'
      },
      {
        name: '京东优选',
        path: '/app/v2/shop/systemChose'
      }
    ],
    systemitems:[],
    syspage:1,
    itemsloading: true,
    systemLoading: true,
    shareItem:[],
    showShare: false,
    imgSrc: '',
    showshareBox: false,
    shareItems2: [],
    thisfreeTxt: '',
    mystoretabtop: '',
    fixed: false
  },
  onShareAppMessage: function () {
    var path= '/pages/shareShop/shareShop?userId=' + this.data.fromUserId
    var title = this.data.shopInfo.ownerName + '的小铺砸锅卖铁打折了，快来看看吧'
    var imageUrl = this.data.imgSrcSmall
    return {
      title: title,
      path: path,
      imageUrl: imageUrl
    }
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '店铺加载中',
    })
    if (options){
      console.log(options)
      this.setData({
        fromUserId: options.userId
      })
    }
    this.getShopInfo()
  },
  onShow() {
    let query = wx.createSelectorQuery()
    query.select('.tabNav').boundingClientRect( (rect) => {
      console.log(rect)
      this.setData({
        mystoretabtop: rect.top - rect.height
      })
      app.globalData.mystoretabtop = rect.top - rect.height
    }).exec()
    // wx.hideHomeButton()
  },
  getShopInfo(){
    const that = this
    common.post({
      url: '/app/v2/shop/shopInfo', data: { userId: this.data.fromUserId }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == "0") {
          that.setData({
            shopInfo: res.data.data,
          })
          that.getShopItem()
          that.getFreeitems()
          that.getsystemItem()
          let promise = new Promise((resolve, reject) => {
            let timer = setInterval(() => {
              // console.log(app.globalData.sessionId,app.globalData.userId)
              // console.log(that.data.systemitems)
              if (that.data.items.length > 0 && that.data.freeitems.length > 0 && that.data.systemitems.length > 0) {
                clearInterval(timer);
                resolve(app.globalData);
                console.log('获取数据完成')
                that.setData({
                  showShare: true
                })
              } else {
                //todo 信息构建中
              }
            }, 250);
          });
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  getShopItem(){
    const that = this
    common.post({
      url: '/app/v2/shop/list', data: { userId: this.data.fromUserId, pageNo: 1 }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          that.setData({
            items: res.data.data,
          })
          if(res.data.total < 11){
            that.setData({
              itemsloading: false
            })
          }
          wx.hideLoading()
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
  },
  getShopItemPage() {
    const that = this;
    var page = that.data.page + 1;
    common.post({ url: '/app/v2/shop/list', data: { userId: this.data.fromUserId, pageNo: page } })
      .then((res) => {
        var data = that.data.items;
        console.log(res.data)
        if (that.data.page * 10 < res.data.total) {
          that.setData({
            page: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            console.log(data)
            that.setData({
              items: data,
            })
          }
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            itemsloading: false
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  searchScrollLower() {
    this.getShopItemPage()
  },
  buybtn(e) {
    console.log(e)
    console.log('/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId + '&userId=' + this.data.fromUserId + '&fO=fsk')
    wx.navigateTo({
      url: '/pages/itemdetailNew/itemdetailNew?sku=' + e.currentTarget.dataset.item.skuId + '&userId=' + this.data.fromUserId + '&fO=fsk',
      success(res){
        console.log(res)
      }
    })
  },
  buybtn2(e) {
    console.log(e)
    // app.globalData.item = e.currentTarget.dataset.item
    console.log('/pages/freeItemdetail/freeItemdetail?sku=' + e.currentTarget.dataset.item.skuId + '&userId=' + this.data.fromUserId + '&fO=fsk')
    wx.navigateTo({
      url: '/pages/freeItemdetail/freeItemdetail?sku=' + e.currentTarget.dataset.item.skuId + '&userId=' + this.data.fromUserId + '&fO=fsk'
    })
  },
  loginTip() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '你需要登录，才能享受优惠',
      success(res) {
        if (res.confirm) {
          console.log('用户点击确定')
          that.runLogin()
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  runLogin() {
    const that = this
    let res = app.login(app.globalData.thisshareTicket)
    let promise = new Promise((resolve, reject) => {
      let timer = setInterval(() => {
        // console.log(app.globalData.sessionId,app.globalData.userId)
        if (app.globalData.sessionId && app.globalData.userId) {
          clearInterval(timer);
          resolve(app.globalData);
          console.log('登录')
          this.getShopInfo()
        } else {
          //todo 信息构建中
        }
      }, 250);
    });
  },
  moreItem(){
    wx.navigateTo({
      url: '/pages/allItemList/allItemList',
      success: function (res) {
        console.log('toAllItemList')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toMyStone() {
    wx.switchTab({
      url: '/pages/myStore/myStore',
      success: function (res) {
        console.log('toMyStore')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  toIndex(){
    wx.switchTab({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        console.log('toItemlist')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  getFreeitems() {
    const that = this
    common.post({ url: '/app/v2/shop/free99', data: { userId: this.data.fromUserId, pageNo: 1,pageSize: 9 } })
      .then((res) => {
        console.log(res.data)
        // var data=[]
        // console.log(res.data)
        // var subdata = res.data.data
        // for(let i=0; i<subdata.length; i+=3){
        //   data.push(subdata.slice(i,i+3))
        // }
        // console.log(data)
        that.setData({
          freeitems: res.data.data
        });
        console.log(that.data.freeitems)
      }).catch((res) => {
        console.log(res)
      })
      
  },
  getFreeitemsPage() {
    const that = this;
    var page = that.data.freePage + 1;
    common.post({ url: '/app/v2/shop/free99', data: { userId: this.data.fromUserId, pageNo: page,pageSize: 9 } })
      .then((res) => {
        var data = [];
        console.log(res.data)
        if (that.data.page * 10 < res.data.total) {
          that.setData({
            freePage: page
          });
          var j = page + 1
          var postList = res.data.data;
          var rdata=[],subdata=[]
          for(let i=0; i<postList.length; i+=3){
            let tmp = postList[i];
            subdata.push(tmp)
            console.log(subdata)
            rdata.push(postList.slice(i,i+3))
          }
          var arr = [...that.data.freeitems,...rdata]
          that.setData({
            freeitems: arr,
          })
          console.log(that.data.freeitems)
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  swChange(e) {
    console.log(e,e.detail.current,e.target.dataset.length)
    this.setData({
      currentTab: e.detail.current
    })
    if (e.detail.current == e.target.dataset.length - 1) {
      console.log('分页')
      this.getFreeitemsPage()
    }
  },
  toAllitem(){
    wx.reLaunch({
      url: '/pages/itemlist/itemlist',
      success: function (res) {
        console.log('toIndex')
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  tabChange(e){
    console.log(e)
    var num = e.currentTarget.dataset.index
    this.setData({
      urlpath: e.currentTarget.dataset.path
    })
    this.setData({
      navTab: num
    })
    if(num == 0){
      this.getShopItem()
    }else if(num == 1){
      this.getsystemItem()
    }
  },
  getsystemItem() {
    this.setData({
      loading: true
    })
    const that = this
    common.post({
      url: '/app/v2/shop/systemChose', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo:1 }
    })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data.total)
          that.setData({
            systemitems: res.data.data,
          })
          if(res.data.total < 11){
            that.setData({
              systemLoading: false
            })
          }
          // wx.hideLoading()
        } else if (res.data.code == "-9998") {
          that.loginTip()
        } else {
          console.log(res)
        }
      }).catch((res) => {
        console.log(res)
      })
  },
  getsystemItemPage() {
    const that = this;
    var page = that.data.syspage + 1;
    common.post({ url: '/app/v2/shop/systemChose', data: { sessionId: app.globalData.sessionId, userId: app.globalData.userId, pageNo: page } })
      .then((res) => {
        var data = that.data.systemitems;
        console.log(res.data)
        if (that.data.syspage * 10 < res.data.total) {
          that.setData({
            syspage: page
          });
          var postList = res.data.data;
          for (let i = 0; i < postList.length; i++) {
            let tmp = postList[i];
            data.push(tmp);
            console.log(data)
            that.setData({
              systemitems: data,
            })
          }
        } else {
          console.log('没有了')
          wx.showToast({
            title: '没有了',
            icon: 'none',
            duration: 2000
          })
          that.setData({
            systemLoading: false
          })
        }

      }).catch((res) => {
        console.log(res)

      })
  },
  onReachBottom() {
    if(this.data.navTab == 0){
      this.getShopItemPage()
    }else{
      this.getsystemItemPage()
    }
  },
  toSearch(){
    wx.navigateTo({
      url: '/pages/seach/seach'
    })
  },
  closeTip(){
    this.setData({
      showShare: false
    })
  },
  shareShop(){
    if(this.data.items.length > 0 && this.data.freeitems.length > 0 && this.data.systemitems.length > 0){
      wx.showLoading({
        title: '生成中...',
        mask: true
      })
      var freeitems = this.data.freeitems,
      systemItems = this.data.systemitems
      items = this.data.items,
      sub1 = [],sub2=[],sub3=[],shareItems=[],shareItems2=[]
      if(freeitems.length > 2){
        console.log('免单商品3个以上')
        sub1 = freeitems.slice(0,3);
        this.setData({
          thisfreeTxt: '0元购'
        })
        shareItems2 = sub1
        if(items.length > 2){
          console.log('小铺商品3个以上')
          sub2 = items.slice(0,3);
          shareItems = [...sub1,...sub2]
        }else{
          console.log('小铺商品不足3个')
          for(let i=0;i<items.length;i++){
            sub2.push(items[i])
          }
          var num = 3 - items.length
          for(let i=0;i<num;i++){
            sub3.push(systemItems[i])
          }
          shareItems = [...sub1,...sub2,...sub3]
        }
      }else{
        console.log('免单商品不足3个')
        this.setData({
          thisfreeTxt: '上新'
        })
        for(let i=0; i<freeitems.length; i++){
          sub1.push(freeitems[i]) 
        }
        var num = 6 - freeitems.length
        if(items.length > num){
          console.log('小铺商品加免单商品6个以上')
          sub2 = item.slice(0,num);
          shareItems = [...sub1,...sub2]
        }else{
          console.log('小铺商品加免单商品不足6个')
          console.log(systemItems)
          for(let i=0; i<items.length; i++){
            sub2.push(items[i]) 
          }
          for(let i=0; i<num; i++){
            sub3.push(systemItems[i])
          }
          shareItems = [...sub1,...sub2,...sub3]
        }
        if(items.length > 3){
          sub2 = items.slice(0,3);
          shareItems2 = sub2
        }else if(items.length > 0){
          var num = 3 - freeitems.length
          for(let i=0; i<items.length; i++){
            sub2.push(items[i]) 
          }
          for(let i=0; i<num; i++){
            sub3.push(systemItems[i])
          }
          shareItems2 = [...sub2,...sub3]
        }else{
          sub2 = systemItems.slice(0,3);
        }
      }
      console.log(shareItems)
      console.log(shareItems2)
      this.setData({
        shareItem: shareItems,
        shareItem2: shareItems2
      })
      console.log('选择画布')
      const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
      query.select('#canvas').fields({
        node: true,
        rect: true
      }, res => {
        const canvas = res.node;
        const ctx = canvas.getContext('2d');
        canvas.width = 828;//本地图像的width
        canvas.height = 1472;//本地图像的height
        this.render(canvas, ctx);
      }).exec()
    }else{
      wx.showModal({
        title: '提示',
        content: '数据还没有加载完成，请稍后...',
        showCancel: false,
        success (res) {
          if (res.confirm) {
            console.log('用户点击确定')
          }
        }
      })
    }
    
  },
  canvas1(){
    console.log('选择画布')
    const query = wx.createSelectorQuery();//如果是在组件中，则改成 this.createSelectorQuery()
    query.select('#canvas1').fields({
      node: true,
      rect: true
    }, res => {
      const canvas = res.node;
      const ctx = canvas.getContext('2d');
      canvas.width = 500;//本地图像的width
      canvas.height = 400;//本地图像的height
      this.render2(canvas, ctx);
    }).exec()
  },
   // 生成分享图

   render(canvas, ctx) {
    const that = this
    this.drawIteminfo(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawShopInfo(ctx,canvas).then(function(){
        console.log('第二步完成')
        that.drawshopkeeper(ctx,canvas).then(function(){
          console.log('第三步完成')
          that.drawDcode(ctx,canvas).then(function(){
            console.log('第四步完成')
            that.drawItem(ctx,canvas,0).then(function(){
              console.log('第五步完成')
              that.drawItem(ctx,canvas,1).then(function(){
                console.log('第六步完成')
                that.drawItem(ctx,canvas,2).then(function(){
                  console.log('第七步完成')
                  that.drawItem(ctx,canvas,3).then(function(){
                    console.log('第八步完成')
                    that.drawItem(ctx,canvas,4).then(function(){
                      console.log('第九步完成')
                      that.drawItem(ctx,canvas,5).then(function(){
                        console.log('第十步完成')
                        that.drawTag(ctx,canvas).then(function(){
                          console.log('第十一步完成')
                          that.drawCanvas(canvas)
                        })
                        
                      })
                    })
                  })
                })
              })
            })
          })
        })
      })
      // that.canvas1()
    })
  },
  render2(canvas, ctx){
    const that = this
    that.drawSmallpic(ctx,canvas).then(function(){
      console.log('第一步完成')
      that.drawItemSmall(ctx,canvas,0).then(function(){
        console.log('第二步完成')
        that.drawItemSmall(ctx,canvas,1).then(function(){
          console.log('第三步完成')
          that.drawItemSmall(ctx,canvas,2).then(function(){
            console.log('第四步完成')
            that.drawCanvas2(canvas)
          })
        })
      })
    })
  },
  drawIteminfo(ctx,canvas){
    console.log('开始绘图')
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();//canvas 2d 通过此函数创建一个图片对象
      img.onload = (e) => {
        console.log('img loaded')
        ctx.drawImage(img, 0, 0, 828, 1472);
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = '/img/new/shop_share@3x.jpg'
    })
  },
  drawShopInfo(ctx,canvas){
    const that = this
    let txt1 = this.data.shopInfo.shopName
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 72, x = 342, y = 60
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 142, 142);
        ctx.restore()
        console.log('绘制头像完成')
        ctx.strokeStyle = "#ffffff";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "44px PingFangSC-Semibold";
        }else{
          ctx.font = "bold 44px NotoSans-Bold";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'center';
        ctx.textBaseline = 'middle';
        ctx.fillText(txt1, 414, 238);
        console.log('绘制文字完成')
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  drawTag(ctx,canvas){
    let txt2 = this.data.shopInfo.fansCount + '位粉丝'
    let x = 352,y = 276, r = 4, w = 126, h = 40
    return new Promise(function (resolve, reject) {
      ctx.beginPath()
      ctx.save()
      // ctx.beginPath()
      // 因为边缘描边存在锯齿，最好指定使用 transparent 填充
      // 这里是使用 fill 还是 stroke都可以，二选一即可
      // ctx.fillStyle = 'transparent'
      ctx.fillStyle = 'transparent'
      // 左上角
      ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
      // 右上角
      ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
      // 右下角
      ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
      // 左下角
      ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
      ctx.fillStyle = 'rgba(255, 255, 255, 0.2)'
      ctx.fill()
      ctx.closePath()
      // 剪切
      ctx.clip()
      ctx.restore();
      if(app.globalData.isIphone){
        ctx.font = "22px PingFangSC-Semibold";
      }else{
        ctx.font = "bold 22px NotoSans-Bold";
      }
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillStyle = "#fff";
      ctx.fillText(txt2, 414, 296);
      ctx.closePath();
      resolve()
    })
  },
  // 绘制头像
  drawshopkeeper(ctx,canvas){
    const that = this
    let txt1 = this.data.shopInfo.ownerName + ' 邀请你进入他的小店',
        txt2 = '长按识别二维码进入小店'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        let r = 46, x = 42, y = 1318
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        if(app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Medium";
        }else{
          ctx.font = "26px NotoSans-Medium";
        }
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(txt1, 148, 1358);
        if(!app.globalData.isIphone){
          ctx.font = "26px PingFangSC-Light";
        }else{
          ctx.font = "lighter 26px NotoSans";
        }
        ctx.fillText(txt2, 148, 1394);
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  // 绘制二维码
  drawDcode(ctx,canvas){
    const that = this
    return new Promise(function (resolve, reject) {
      var scene = 'userId=' + that.data.fromUserId
      common.post({
        url: '/wxa/qrcode/getUnlimitQrcode', 
        data: {
          scene: scene,
          // page: 'pages/shareShop/shareShop',
          page: 'pages/itemlist/itemlist',
          sessionId: app.globalData.sessionId,
          width: '236',
          auto_color: 'false',
          line_color: '{"r":"255","g":"85","b":"85"}',
          is_hyaline: 'false'
        }
      })
      .then((res) => {
        console.log(res.data)
        if (res.data.code == 0) {
          console.log(res.data)
          console.log(res.data.qrcodeLink)
          let img = canvas.createImage();
          img.onload = (e) => {
            console.log('img loaded')
            ctx.beginPath()
            let r = 68, x = 652, y = 1296
            ctx.save()
            ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
            ctx.fillStyle = 'white'
            ctx.fill()
            ctx.clip()
            ctx.drawImage(img, x + 7, y + 7, 122, 122);
            ctx.restore()
            ctx.closePath();
            resolve()
          }
          img.onerror = (e) => {
            console.error('err:', e)
          }
          img.src = res.data.qrcodeLink
        }else{
          wx.hideLoading()
          that.loginTip()
        }
      }).catch((res) => {
        console.log(res)
        app.timeOutTip()
      })
    })
  },
  // 绘制商品图1
  drawItem(ctx,canvas,i){
    const that = this
    var row1size = function (name) {
      var str = name;
      // str = str.slice(0, 36) + '...';
      length = 0.0;
      finalStr = "";
      for (i = 0; i < name.length; i++) {
        if (name[i].match("[0-9a-zA-Z]") || name[i] == " ") {
          length += 0.5;
        } else {
          length += 1;
        }
        finalStr += name[i];
        if (length > 8) {
          break;
        }
      }
      return finalStr;
    }
    var findcoupons = function (coupons) {
      var val=0;
      if(coupons.length == 1){
          return val = coupons[0].discount
      }else {
          for(var i=0; i < coupons.length; ++i){
              if(val < coupons[i].discount){
                  val = coupons[i].discount
              }
          }
          return val
      }
    }
    var format = function(value){
      var html,_val;
      value =Number(value).toFixed(1);
      if(value==0){
          value=0;
          return html = "0";
      }else {
          value = Number(value).toFixed(1);
      }
      _val = value.split('.');
      return html = _val[0]+'.'+_val[1];
    }
    switch(i){
      case 0:
        var x = 48,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 120, circleY = 784, circleR = 20,
            circleX2 = 204, 
            rectangleX = 120, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 162, txt1Y = 740,
            txt2X = 162, txt2Y = 786,
            priceNewX = 159, priceNewY = 795,
            priceOldX = 165, priceOldY = 797
        break;
      case 1:
        var x = 300,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 372, circleY = 784, circleR = 20,
            circleX2 = 456, 
            rectangleX = 372, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 414, txt1Y = 740,
            txt2X = 414, txt2Y = 786,
            priceNewX = 413, priceNewY = 795,
            priceOldX = 417, priceOldY = 797
        break;
      case 2:
        var x = 552,y = 488, r = 8, w = 228, h = 228,
            circleX1 = 584, circleY = 784, circleR = 20,
            circleX2 = 668, 
            rectangleX = 584, rectangleY = 764, rectangleW = 84, rectangleH = 40,
            txt1X = 667, txt1Y = 740,
            txt2X = 667, txt2Y = 786,
            priceNewX = 664, priceNewY = 795,
            priceOldX = 670, priceOldY = 797
        break;
      case 3:
        var x = 48,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 120, circleY = 1174, circleR = 20,
            circleX2 = 204, 
            rectangleX = 120, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 162, txt1Y = 1134,
            txt2X = 162, txt2Y = 1176,
            priceNewX = 159, priceNewY = 1185,
            priceOldX = 165, priceOldY = 1187
        break;
      case 4:
        var x = 300,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 372, circleY = 1174, circleR = 20,
            circleX2 = 456, 
            rectangleX = 372, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 414, txt1Y = 1134,
            txt2X = 414, txt2Y = 1176,
            priceNewX = 413, priceNewY = 1185,
            priceOldX = 417, priceOldY = 1187
        break;
      case 5:
        var x = 552,y = 878, r = 8, w = 228, h = 228,
            circleX1 = 584, circleY = 1174, circleR = 20,
            circleX2 = 668, 
            rectangleX = 584, rectangleY = 1154, rectangleW = 84, rectangleH = 40,
            txt1X = 667, txt1Y = 1134,
            txt2X = 667, txt2Y = 1176,
            priceNewX = 664, priceNewY = 1185,
            priceOldX = 670, priceOldY = 1187
        break;
    }
    console.log(i)
    console.log(that.data.shareItem[i])
    var item = that.data.shareItem[i]
    var txt1 = row1size(item.title),
        txt2 = '限时免单'
    var priceNew = '',
        priceOld = '￥' + item.price
    var lineWidth = ctx.measureText(priceOld)
    if(item.coupons){
      priceNew = '￥' + format(item.price - findcoupons(item.coupons))
    }else{
      priceNew = '￥' + priceOld
    }
    
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        ctx.beginPath()
        console.log('img loaded')
        ctx.save()
        ctx.setFillStyle = 'transparent'
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.closePath()
        ctx.clip()
        ctx.drawImage(img, x, y, w, h);
        ctx.restore();
        ctx.beginPath()
        if(app.globalData.isIphone){
          ctx.font = "23px PingFangSC-Medium";
        }else{
          ctx.font = "23px NotoSans-Medium";
        }
        ctx.fillStyle = "#505050";
        ctx.textAlign = 'center';
        ctx.fillText(txt1, txt1X, txt1Y);
        console.log(item.is99)
        if(item.is99){
          ctx.arc(circleX1,circleY,circleR,0,2*Math.PI)
          ctx.fillStyle = "#FFE232"
          ctx.fill()
          ctx.arc(circleX2,circleY,circleR,0,2*Math.PI)
          ctx.fillStyle = "#FFE232"
          ctx.fill()
          ctx.fillRect(rectangleX,rectangleY,rectangleW,rectangleH)
          ctx.fillStyle = "#000";
          ctx.fillText(txt2, txt2X, txt2Y);
        }else{
          if(app.globalData.isIphone){
            ctx.font = "27px PingFangSC-Semibold";
          }else{
            ctx.font = "bold 27px NotoSans-Bold";
          }
          ctx.fillStyle = "#FF5555";
          ctx.textAlign = 'right';
          ctx.fillText(priceNew, priceNewX, priceNewY);
          if(app.globalData.isIphone){
            ctx.font = "23px PingFangSC-Semibold";
          }else{
            ctx.font = "bold 23px NotoSans-Bold";
          }
          ctx.fillStyle = "#BCBCBC";
          ctx.textAlign = 'left';
          ctx.fillText(priceOld, priceOldX, priceOldY);
          ctx.fillStyle = "#BCBCBC";
          ctx.fillRect(priceOldX, priceOldY - 4, lineWidth.width, 2)
        }
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  // 生成图片
  drawCanvas(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 828,
        height: 1472,
        destWidth:828,
        destHeight:1472,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrc:res.tempFilePath,
          })
          that.canvas1()
          // wx.hideLoading()
        }
      })
    })
  },
  // 绘制分享小图
  drawSmallpic(ctx,canvas){
    const that = this
    let shopName = this.data.shopInfo.shopName,
        txt1 = '以上为今日' + this.data.thisfreeTxt + '的商品哦',
        txt2 = '快来看看吧！'
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        console.log('img loaded')
        ctx.beginPath()
        ctx.fillStyle = '#FF5555'
        ctx.fillRect(0,0,500,400)
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillStyle = "#fff";
        ctx.textAlign = 'left';
        ctx.fillText(shopName, 128, 68);
        ctx.textAlign = 'center';
        ctx.font = "bold 32px PingFangSC-Semibold";
        ctx.fillStyle = '#FFF617'
        ctx.fillText(txt1, 250, 334);
        ctx.font = "bold 24px PingFangSC-Semibold";
        ctx.fillText(txt2, 250, 368);
        let r = 46, x = 9, y = 9
        ctx.save()
        ctx.arc(x + r, y + r, r, 0, 2 * Math.PI)
        ctx.clip()
        ctx.drawImage(img, x, y, 92, 92);
        ctx.restore()
        ctx.strokeStyle = "white";
        ctx.lineWidth = '2'
        ctx.stroke();
        ctx.closePath();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = that.data.shopInfo.avatar
    })
  },
  drawItemSmall(ctx,canvas,i){
    const that = this
    switch(i){
      case 0:
        var x = 16,y = 136, r = 4, w = 152, h = 152
        break;
      case 1:
        var x = 174,y = 136, r = 4, w = 152, h = 152
        break;
      case 2:
        var x = 332,y = 136, r = 4, w = 152, h = 152
        break;
    }
    console.log(i)
    console.log(that.data.shareItem[i])
    var item = that.data.shareItem[i]
    return new Promise(function (resolve, reject) {
      let img = canvas.createImage();
      img.onload = (e) => {
        ctx.beginPath()
        console.log('img loaded')
        ctx.save()
        ctx.setFillStyle = 'transparent'
        ctx.arc(x + r, y + r, r, Math.PI, Math.PI * 1.5)
        ctx.arc(x + w - r, y + r, r, Math.PI * 1.5, Math.PI * 2)
        ctx.arc(x + w - r, y + h - r, r, 0, Math.PI * 0.5)
        ctx.arc(x + r, y + h - r, r, Math.PI * 0.5, Math.PI)
        ctx.closePath()
        ctx.clip()
        ctx.drawImage(img, x, y, w, h);
        ctx.restore();
        resolve()
      }
      img.onerror = (e) => {
        console.error('err:', e)
      }
      img.src = item.image
    })
  },
  drawCanvas2(canvas){
    const that = this
    let promise = new Promise(function (resolve, reject) {
      wx.canvasToTempFilePath({
        canvas,
        wwidth: 500,
        height: 400,
        destWidth:500,
        destHeight:400,
        success(res) {
          console.log(res.tempFilePath)
          that.setData({
            imgSrcSmall:res.tempFilePath,
            showshareBox: true
          })
          wx.hideLoading()
        }
      })
    })
  },
  saveSharePic(){
    wx.saveImageToPhotosAlbum({
      filePath: this.data.imgSrc,
      success: function (data) {
          wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
          })
      },
      fail: function (err) {
          console.log(err);
          if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
              console.log("当初用户拒绝，再次发起授权")
              wx.openSetting({
                  success(settingdata) {
                      console.log(settingdata)
                      if (settingdata.authSetting['scope.writePhotosAlbum']) {
                          console.log('获取权限成功，给出再次点击图片保存到相册的提示。')
                      } else {
                          console.log('获取权限失败，给出不给权限就无法正常使用的提示')
                      }
                  }
              })
          } else {
              wx.showToast({
                  title: '保存失败',
                  icon: 'none'
              });
          }
      },
      complete(res) {
          console.log(res);
      }
    })
  },
  closeSharePic(){
    console.log('关闭')
    this.setData({
      showshareBox: false
    })
  },
  jlshare(e){
    console.log(e)
    const that = this
    wx.navigateTo({
      url: '/pages/createSolitaire/createSolitaire',
      events: {
        acceptDataFromOpenedPage: function (data) {
          console.log(data)
        },
        someEvent: function (data) {
          console.log(data)
        }
      },
      success: function (res) {
        console.log('toCreateSolitaire')
        res.eventChannel.emit('acceptDataFromOpenerPage', { data: e.currentTarget.dataset.item })
      },
      fail: function (res) {
        console.log(res)
      }
    })
  },
  onPageScroll: function (e) {
    if(e.scrollTop >= this.data.mystoretabtop){
      if(!this.data.fixed){
        this.setData({
          fixed: true
        })
      }
    }else{
      if(this.data.fixed){
        this.setData({
          fixed: false
        })
      }
    }
  },
})